import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import type { Algorithm, AlgorithmSolution, CreateAlgorithmRequest } from '@/types/algorithm'
import * as algorithmsApi from '@/api/algorithms'

export const useAlgorithmsStore = defineStore('algorithms', () => {
  // 状态
  const problems = ref<Algorithm[]>([])
  const currentProblem = ref<Algorithm | null>(null)
  const currentSolution = ref<AlgorithmSolution | null>(null)
  const isLoading = ref(false)
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  
  // 筛选条件
  const filters = ref({
    difficulty: '',
    search: ''
  })

  // 计算属性
  const filteredProblems = computed(() => {
    let result = problems.value
    
    if (filters.value.difficulty) {
      result = result.filter(p => p.difficulty === filters.value.difficulty)
    }
    
    if (filters.value.search) {
      const search = filters.value.search.toLowerCase()
      result = result.filter(p => 
        p.title.toLowerCase().includes(search) ||
        p.description.toLowerCase().includes(search)
      )
    }
    
    return result
  })

  const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

  // 获取算法题列表
  const fetchProblems = async (params?: {
    page?: number
    limit?: number
    difficulty?: string
    search?: string
  }) => {
    try {
      isLoading.value = true
      const response = await algorithmsApi.getAlgorithms({
        page: currentPage.value,
        limit: pageSize.value,
        ...params
      })
      
      if (response.success && response.data) {
        problems.value = response.data.problems
        total.value = response.data.total
        currentPage.value = response.data.page
        pageSize.value = response.data.limit
      }
    } catch (error) {
      console.error('Failed to fetch problems:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取单个算法题详情
  const fetchProblem = async (id: number) => {
    try {
      isLoading.value = true
      const response = await algorithmsApi.getAlgorithm(id)
      
      if (response.success && response.data) {
        currentProblem.value = response.data
        return response.data
      }
    } catch (error) {
      console.error('Failed to fetch problem:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建算法题
  const createProblem = async (data: CreateAlgorithmRequest) => {
    try {
      isLoading.value = true
      const response = await algorithmsApi.createAlgorithm(data)
      
      if (response.success && response.data) {
        problems.value.unshift(response.data)
        total.value += 1
        return response.data
      }
    } catch (error) {
      console.error('Failed to create problem:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 更新算法题
  const updateProblem = async (id: number, data: Partial<CreateAlgorithmRequest>) => {
    try {
      isLoading.value = true
      const response = await algorithmsApi.updateAlgorithm(id, data)
      
      if (response.success && response.data) {
        const index = problems.value.findIndex(p => p.id === id)
        if (index !== -1) {
          problems.value[index] = response.data
        }
        if (currentProblem.value?.id === id) {
          currentProblem.value = response.data
        }
        return response.data
      }
    } catch (error) {
      console.error('Failed to update problem:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 删除算法题
  const deleteProblem = async (id: number) => {
    try {
      isLoading.value = true
      await algorithmsApi.deleteAlgorithm(id)
      
      problems.value = problems.value.filter(p => p.id !== id)
      total.value -= 1
      
      if (currentProblem.value?.id === id) {
        currentProblem.value = null
        currentSolution.value = null
      }
    } catch (error) {
      console.error('Failed to delete problem:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取代码解决方案
  const fetchSolution = async (problemId: number) => {
    try {
      const response = await algorithmsApi.getCode(problemId)
      
      if (response.success && response.data) {
        currentSolution.value = response.data
        return response.data
      }
    } catch (error) {
      // 如果没有找到解决方案，不抛出错误
      if (error instanceof Error && error.message.includes('404')) {
        currentSolution.value = null
        return null
      }
      console.error('Failed to fetch solution:', error)
      throw error
    }
  }

  // 保存代码解决方案
  const saveSolution = async (problemId: number, code: string) => {
    try {
      const response = await algorithmsApi.saveCode(problemId, code)
      
      if (response.success && response.data) {
        currentSolution.value = response.data
        return response.data
      }
    } catch (error) {
      console.error('Failed to save solution:', error)
      throw error
    }
  }

  // 设置筛选条件
  const setFilters = (newFilters: Partial<typeof filters.value>) => {
    filters.value = { ...filters.value, ...newFilters }
  }

  // 重置筛选条件
  const resetFilters = () => {
    filters.value = {
      difficulty: '',
      search: ''
    }
  }

  // 设置当前页
  const setCurrentPage = (page: number) => {
    currentPage.value = page
  }

  return {
    // 状态
    problems: readonly(problems),
    currentProblem: readonly(currentProblem),
    currentSolution: readonly(currentSolution),
    isLoading: readonly(isLoading),
    total: readonly(total),
    currentPage: readonly(currentPage),
    pageSize: readonly(pageSize),
    filters: readonly(filters),
    
    // 计算属性
    filteredProblems,
    totalPages,
    
    // 方法
    fetchProblems,
    fetchProblem,
    createProblem,
    updateProblem,
    deleteProblem,
    fetchSolution,
    saveSolution,
    setFilters,
    resetFilters,
    setCurrentPage
  }
})